package com.example.chat.service.impl;

import com.dragonsoftbravo.web.PageVO;
import com.example.chat.constant.ErrorCode;
import com.example.chat.model.User;
import com.example.chat.model.ro.UserListRO;
import com.example.chat.model.ro.UserRo;
import com.example.chat.model.vo.UserListVO;
import com.example.chat.model.vo.UserVO;
import com.example.chat.repository.UserRepository;
import com.example.chat.service.CodeMessageService;
import com.example.chat.service.UserService;
import com.example.chat.type.DataStatusEnum;
import com.example.chat.utils.ChatException;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author pq
 * @date 2022/8/14 1:07
 * @description
 * @modified
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserRepository UserRepository;

    @Resource
    CodeMessageService codeMessageService;

    @Resource
    UserRepository userRepository;

    @Override
    public void add(UserRo ro) {
        UserRepository.findByNicknameAndDataStatus(ro.getNickname(),DataStatusEnum.effective.getCode()).ifPresent(User ->
        {
            throw new ChatException(HttpStatus.OK.value(), ErrorCode.USER_EXISTED,codeMessageService.message(ErrorCode.USER_EXISTED));
        });
        User User=new User();
        BeanUtils.copyProperties(ro,User);
        UserRepository.save(User);
    }

    @Override
    public PageVO<UserListVO> UserList(UserListRO UserListRO, String currentUserId) {
        UserListRO.setSort(Sort.by(Sort.Order.desc("nickname")));
        Page<UserListVO> UserPage=UserRepository.findByPage(UserListRO,UserListRO.pageable());
        PageVO<UserListVO> pageVO=new PageVO<>();
        pageVO.setContent(UserPage.getContent());
        return pageVO;
    }

    @Override
    public Page<UserVO> find(User user) {
        PageRequest pageable = PageRequest.of(0, 10, Sort.by(Sort.Order.desc("id")));
//        return userRepository.queryUsers(user,pageable);
        return null;
    }
}
